<template>
  <div class="app-container">
    <div class="box1">
      <button
        v-for="(item, index) in goodsList"
        :key="'goods-' + index"
        class="custom-button"
        :class="{ active: selectedGoods === item }"
        @click="selectGoods(item)"
      >
        {{ item.name }}
      </button>
    </div>
    <div class="box2">
      <button
        v-for="(items, indexs) in DepotList"
        :key="'depot-' + indexs"
        class="custom-button1"
        :class="{ active: selectedDepot === items }"
        @click="selectDepot(items)"
      >
        {{ items.name }}
      </button>
    </div>
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商城sku" prop="sku">
        <el-input
          v-model="queryParams.sku"
          placeholder="请输入商品代号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          :icon="isSyncing? 'el-icon-loading' : 'el-icon-refresh'"
          size="mini"
          @click="synchronousGood"
          v-has-permi="['erp:erp:synch']"
          :disabled="isGettingNoodle"
        >同步商品</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['erp:good:add']"
        >新增</el-button>
      </el-col>
     <el-col :span="1.5">
       <el-button
         type="primary"
         plain
         icon=""
         size="mini"
         @click="autoMapping"
         :disabled="isGettingNoodle"
         >自动映射</el-button>
     </el-col>
      <div style="background-color: #FFEDED; color: #ff4949; display: inline-block; padding: 5px; font-size: 13px">
        最后同步时间:{{sysTimeList && sysTimeList.syncTime? sysTimeList.syncTime : ''}}
      </div>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="goodList" @selection-change="handleSelectionChange">
<!--      <el-table-column type="selection" width="55" align="center" />-->
      <el-table-column label="店铺代号" align="center" prop="mallCode" />
      <el-table-column label="选中的商品" align="center" :label="selectedGoodsName" prop="sku"/>
      <el-table-column label="选中的商品" align="center" :label="selectedDepotName" prop="depotSku" width="500px">
        <template slot-scope="scope">
          <div v-for="(item, index) in scope.row.tbErpGoodMapList" :key="index" class="input-group">
            <span class="label">SKU</span>
            <el-input v-model="item.sku" placeholder="输入SKU" class="input"></el-input>
            <span class="label">数量</span>
            <el-input v-model="item.skuNumber" placeholder="输入数量" class="input"></el-input>
            <el-button @click="addSkuQuantity(scope.$index)" icon="el-icon-plus" class="add-button"></el-button>
            <el-button @click="deleteSkuQuantity(scope.$index, index)" icon="el-icon-minus" class="delete-button"></el-button>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-caret-right"
            @click="mappingSku(scope.row)"
          >sku映射</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['erp:mall:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改店铺商品对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="店铺代号" prop="mallCode">
          <el-input v-model="form.mallCode" placeholder="请输入店铺代号" disabled/>
        </el-form-item>
        <el-form-item label="商品代号(SKU)" prop="sku">
          <el-input v-model="form.sku" placeholder="请输入商品代号" />
        </el-form-item>
        <el-form-item label="商品中文名" prop="nameCn">
          <el-input v-model="form.nameCn" placeholder="请输入商品中文名" />
        </el-form-item>
        <el-form-item label="商品英文名" prop="nameEn">
          <el-input v-model="form.nameEn" placeholder="请输入商品英文名" />
        </el-form-item>
        <el-form-item label="商品俄文名" prop="nameRu">
          <el-input v-model="form.nameRu" placeholder="请输入商品俄文名" />
        </el-form-item>
        <el-form-item label="售价" prop="price">
          <el-input v-model="form.price" placeholder="请输入售价" />
        </el-form-item>
        <el-form-item label="商品图片" prop="img">
          <el-input v-model="form.img" placeholder="请输入商品图片" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listGood, getGood, delGood, addGood, updateGood,getMall,getDePot,synchronousGood,mappings,batchMapper,deleteSku } from "@/api/erp/good";
import {syncTime} from "@/api/erp/order";
export default {
  name: "Good",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      isGettingNoodle: false,
      // 总条数
      total: 0,
      // 店铺商品表格数据
      goodList: [],
      goodsList: [],
      DepotList:[],
      //同步时间数据
      sysTimeList:[],
      selectedGoods: null,
      selectedDepot: null,
      isSyncing: false,
      depotSku:null,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        productId: null,
        mallId: null,
        mallCode: null,
        userId: null,
        sku: null,
        nameCn: null,
        nameEn: null,
        nameRu: null,
        price: null,
        currencyType: null,
        charged: null,
        img: null,
        depotId: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        mallCode:[
          { required: true, message: "店铺代号不能为空", trigger: "blur" }
        ],
        sku: [
          { required: true, message: "商品代号不能为空", trigger: "blur" }
        ],
        nameCn:[
          { required: true, message: "商品中文名不能为空", trigger: "blur" }
        ],
        nameEn:[
          { required: true, message: "商品英文名不能为空", trigger: "blur" }
        ],
        nameRu:[
          { required: true, message: "商品俄文名不能为空", trigger: "blur" }
        ],
        price:[
          { required: true, message: "售价不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getDepots();
    this.getForGoods().then(() => {
      this.selectedGoods = this.goodsList[0];
    });
  },
  computed: {
    selectedGoodsName() {
      return this.selectedGoods ? `${this.selectedGoods.name}商城SKU` : '';
    },
    selectedDepotName(){
      return this.selectedDepot ? `${this.selectedDepot.name}云仓SKU` : '';
    }
  },
  methods: {
    /** 查询店铺商品列表 */
    getList() {
      this.loading = true;
      listGood(this.queryParams).then((response) => {
        // 为返回的每一项数据添加 skuQuantityList 属性
        this.goodList = response.rows.map((item) => ({
          ...item,
          tbErpGoodMapList: item.tbErpGoodMapList || [
            { sku: "", skuNumber: "" }
          ]
        }));
        this.total = response.total;
        this.loading = false;
      });
    },
    getForGoods() {
      this.loading = true;
      return getMall().then(response => {
        this.goodsList = response.data;
        this.loading = false;
        return response;
      });
    },
    getDepots() {
      this.loading = true;
      return getDePot().then(response => {
        this.DepotList = response.data;
        this.loading = false;
        return response;
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        mallGoodId: null,
        productId: null,
        mallId: null,
        mallCode: null,
        userId: null,
        sku: null,
        nameCn: null,
        nameEn: null,
        nameRu: null,
        price: null,
        currencyType: null,
        charged: null,
        img: null,
        createTime: null,
        createBy: null,
        updateTime: null,
        updateBy: null,
        delFlag: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      if (this.selectedGoods && this.selectedGoods.mallId) {
        this.queryParams.mallId = this.selectedGoods.mallId
      }
      if(this.selectedDepot && this.selectedDepot.depotId){
        this.queryParams.depotId=this.selectedDepot.depotId
      }
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.mallGoodId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
      this.selectedGoods = selection[0] || null;
      this.selectedDepot = selection[0] || null;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.form.mallCode=this.selectedGoods.code
      this.title = "添加店铺商品";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const mallGoodId = row.mallGoodId || this.ids
      getGood(mallGoodId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改店铺商品";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.form.mallId=this.selectedGoods.mallId;
      this.form.mallCod=this.selectedGoods.mallCode;
      this.form.productId=1
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.mallGoodId != null) {
            updateGood(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addGood(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const mallGoodIds = row.mallGoodId || this.ids;
      this.$modal.confirm('是否确认删除店铺商品编号为"' + mallGoodIds + '"的数据项？').then(function () {
        return delGood(mallGoodIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    //sku映射
    // mappingSku(row){
    //   const data ={
    //     mallId:row.mallId,
    //     mallGoodProductId:row.productId,
    //     mallGoodSku:row.sku,
    //     sku:row.depotSku,
    //     depotId:this.selectedDepot.depotId
    //   }
    //   if(data.sku ===null || data.sku === undefined){
    //     this.$modal.msgWarning("映射sku不能为空")
    //     return;
    //   }
    //   mappings(data).then(response =>{
    //     if(response.code === 200){
    //       this.$modal.msgSuccess("映射成功")
    //       this.getList()
    //     }
    //   }).catch(() => {
    //     this.$modal.msgError("映射失败")
    //   });
    // },
    mappingSku(row){
      const mappingDataList = row.tbErpGoodMapList.map(item => {
        return {
          mallId: row.mallId,
          mallGoodProductId: row.productId,
          mallGoodSku: row.sku,
          sku: item.sku,
          depotId: this.selectedDepot.depotId,
          skuNumber: item.skuNumber
        };
      });
      console.log(mappingDataList)
        mappings(mappingDataList).then(response =>{
          if(response.code === 200){
            this.$modal.msgSuccess("映射成功")
            this.getList()
          }
        }).catch(() => {
          this.$modal.msgError("映射失败")
        });
    },
    //查询选中的店铺
    selectGoods(item) {
      this.selectedGoods = item;
      this.getNewTime()
      this.handleQuery()
    },
    //查询选中的仓库
    selectDepot(item) {
      this.selectedDepot = item;
      this.handleQuery()
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('erp/good/export', {
        ...this.queryParams
      }, `good_${new Date().getTime()}.xlsx`)
    },
    // 同步商品
    synchronousGood() {
      this.isSyncing = true;
      this.isGettingNoodle=true
      const selectedGoodInfo = this.selectedGoods;
      const data = {
        appKey: selectedGoodInfo.appKey,
        appSecret: selectedGoodInfo.appSecret,
        type: selectedGoodInfo.type,
        mallId: selectedGoodInfo.mallId,
        code: selectedGoodInfo.code
      };
      synchronousGood(data).then(response => {
        if (response.code === 200) {
          this.$modal.msgSuccess("同步成功");
        }
        this.isSyncing = false;
        this.isGettingNoodle=false
        this.getList()
        this.getNewTime()
      }).catch(() => {
        this.isSyncing = false;
      });
    },
    //自动映射
    autoMapping(){
      const mallId =this.selectedGoods.mallId
      const depotId =this.selectedDepot.depotId;
      batchMapper(mallId,depotId).then(response =>{
          if(response.code === 200){
            this.$modal.msgSuccess("映射成功");
          }
          this.getList()
      }).catch(()=>{
        this.$modal.msgError("映射失败")
      })
    },
    //获取最新同步时间
    getNewTime() {
      const mallId =this.selectedGoods.mallId;
      const syncType ='2';
      syncTime(mallId,syncType).then(response =>{
        this.sysTimeList =response.data;
      })
    },
    addSkuQuantity(rowIndex) {
      const currentRow = this.goodList[rowIndex];
      const tbErpGoodMapList = currentRow.tbErpGoodMapList;
      if (tbErpGoodMapList.length < 10) {
        tbErpGoodMapList.push({ sku: '', quantity: '' });
      } else {
        this.$message.warning('每个商品的映射 SKU 数量上限为 10 个，不能再添加了。');
      }
    },
    // 新增删除方法
    deleteSkuQuantity(rowIndex, itemIndex) {
      const currentRow =this.goodList[rowIndex];
      if(currentRow.tbErpGoodMapList.length === 1){
        this.$modal.msgWarning("至少映射一组sku")
        return;
      }
      const itemToDelete = currentRow.tbErpGoodMapList[itemIndex];
      // 检查 sku 和 quantity 是否都为空
      if (!itemToDelete.sku &&!itemToDelete.quantity) {
        // 若都为空，直接删除该行
        currentRow.tbErpGoodMapList.splice(itemIndex, 1);
        return;
      }
      const data ={
        sku:currentRow.tbErpGoodMapList[itemIndex].sku,
        mallGoodSku:currentRow.sku,
        mallId:this.selectedGoods.mallId,
        depotId:this.selectedDepot.depotId
      }
      this.$modal.confirm("您确定要删除这个映射的sku数据吗?").then(function (){
        return deleteSku(data)
      }).then(()=>{
        this.getList();
        this.$modal.msgSuccess("删除成功")
      })
    }
  },
  mounted() {
    this.getForGoods().then(() => {
      this.selectedGoods = this.goodsList[0];
      if (this.selectedGoods && this.selectedGoods.mallId) {
        this.queryParams.mallId = this.selectedGoods.mallId;
      }
      this.getDepots().then(() => {
        this.selectedDepot = this.DepotList[0];
        if (this.selectedDepot && this.selectedDepot.depotId) {
          this.queryParams.depotId = this.selectedDepot.depotId;
        }
        this.handleQuery();
        this.getNewTime();
      });
    });
  }
};
</script>
<style>
.button-container {
  display: flex; /* 使用 Flexbox 来排列按钮 */
}

.custom-button {
  background-color: white; /* 默认背景颜色为白色 */
  color: black; /* 默认文字颜色为黑色 */
  border: 0.5px solid black; /* 默认边框为黑色 */
  padding: 5px 5px;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.3s, color 0.3s, border-color 0.3s;
  min-width: 80px; /* 设置按钮的最小宽度 */
  min-height: 40px; /* 设置按钮的最小高度 */
  display: inline-flex; /* 使按钮大小根据内容调整 */
  align-items: center; /* 垂直居中对齐文字 */
  justify-content: center; /* 水平居中对齐文字 */
  margin: 0;
  margin-right: -2px; /* 消除边框间隙 */
}

.custom-button:hover {
  background-color: white;
  color: #1890FF;
}

.custom-button:active{
  background-color: white;
  color: black;
}
.custom-button:focus {
  background-color: #1890FF; /* 点击或选中时背景颜色变为蓝色 */
  color: white; /* 点击或选中时文字颜色变为白色 */
  border-color: dodgerblue; /* 点击或选中时边框颜色变为蓝色 */
}
.custom-button:not(:last-of-type) {
  border-right: none; /* 去掉按钮之间的右边框 */
}

.custom-button1 {
  background-color: white; /* 默认背景颜色为白色 */
  color: black; /* 默认文字颜色为黑色 */
  border: 1px solid #151515; /* 默认边框为黑色 */
  padding: 10px 20px;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.3s, color 0.3s, border-color 0.3s;
  min-width: 100px; /* 设置按钮的最小宽度 */
  min-height: 40px; /* 设置按钮的最小高度 */
  display: inline-flex; /* 使按钮大小根据内容调整 */
  align-items: center; /* 垂直居中对齐文字 */
  justify-content: center; /* 水平居中对齐文字 */
  margin: 0;
  margin-right: -2px; /* 消除边框间隙 */
}

.custom-button1:hover {
  background-color: white;
  color: #1890FF;
}
.custom-button1:active{
  background-color: white;
  color: black;
}
.custom-button1:focus {
  background-color: #1890FF;
  color: white;
  border-color: dodgerblue;

}
.custom-button1:active {
  background-color: white; /* 点击或选中时背景颜色变为蓝色 */
  color: black; /* 点击或选中时文字颜色变为白色 */
  border-color:skyblue; /* 点击或选中时边框颜色变为蓝色 */
}

.custom-button1:not(:last-of-type) {
  border-right: none; /* 去掉按钮之间的右边框 */
}
.active {
  background-color: dodgerblue;
  color: white;
}
.box1,.box2{
  margin-bottom: 20px;
}
.input-group {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  flex-wrap: nowrap; /* 防止换行 */
}

.label {
  margin-right: 8px;
  min-width: 30px;
  text-align: right;
  white-space: nowrap; /* 防止文本换行 */
}

.input {
  width: 180px; /* 可以根据需要调整宽度 */
  margin-right: 8px;
  min-width: 0; /* 防止输入框溢出 */
}

.add-button {
  white-space: nowrap; /* 防止按钮文本换行 */
  margin-right: 8px;
}

.delete-button {
  white-space: nowrap; /* 防止按钮文本换行 */
}
</style>
